package com.yuandian.management.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.management.mapper.CodeDetailMapper;
import com.yuandian.management.mapper.CodeManagementMapper;
import com.yuandian.management.service.ICodeDetailService;
import com.yuandian.management.vo.CodeDetailsExcelVo;
import com.yuandian.management.vo.CodeDetailsVo;
import com.yuandian.management.vo.CodeManagementParams;
import com.yuandian.management.vo.CodeManagementVo;
import com.yuandian.utils.poi.BatchDataResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 返回码详情
 *
 * @author zhoutian
 * @date 2021/1/26 17:15
 */
@Service
public class CodeDetailServiceImpl implements ICodeDetailService {
    @Autowired
    private CodeDetailMapper codeDetailMapper;
    @Autowired
    private CodeManagementMapper codeManagementMapper;

    private static Map<String, Integer> levelMap = new HashMap<>();
    private static Map<String, Integer> typeMap = new HashMap<>();
    private static Map<Integer,String > typeMap2 = new HashMap<>();
    static {
        levelMap.put("提示", 1);
        levelMap.put("一般", 2);
        levelMap.put("重大", 3);
        levelMap.put("紧急", 4);
        levelMap.put("正常", 5);
        typeMap.put("WEB返回码", 1);
        typeMap.put("中间件返回码", 2);
        typeMap.put("数据库返回码", 3);
        typeMap.put("自定义返回码", 4);
        typeMap2.put(1,"WEB返回码");
        typeMap2.put(2,"中间件返回码");
        typeMap2.put(3,"数据库返回码");
        typeMap2.put(4,"自定义返回码");
    }

    @Override
    public CodeDetailsVo queryCodeDetailsById(Integer id) {
        return codeDetailMapper.queryById(id);
    }

    /**
     * 列表查询
     *
     * @param params 参数
     * @return PageDataInfo
     */
    @Override
    public Page<CodeDetailsVo> queryList(CodeManagementParams params) {
        Page<CodeDetailsVo> page = new Page<>(params.getPageNum(), params.getPageSize());
		Page<CodeDetailsVo> list = codeDetailMapper.queryList(page, params);
        return list;
    }

    /**
     * 根据id 删除
     *
     * @param ids id集
     * @return Result
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R delByIds(Integer[] ids) {
        codeDetailMapper.delByIds(ids);
        codeManagementMapper.updateCount();
        return R.ok();
    }

    /**
     * 保存
     *
     * @param vo 参数
     * @return Result
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R save(CodeDetailsVo vo) {
        //验证返回码值+返回码类型的组合是否重复
        CodeDetailsVo codeDetailsVo = codeDetailMapper.selectByValueAndTypeAndName(vo.getValue(), vo.getTypeId(),vo.getName());
        if (codeDetailsVo != null && !codeDetailsVo.getId().equals(vo.getId())){
            return R.failed(null,"返回码值\""+vo.getValue()+"\"+返回码类型\""+typeMap2.get(vo.getTypeId())+"\"的组合已存在!");
        }
        if (vo.getId() != null && vo.getId() > 0) {
            codeDetailMapper.updateCode(vo);
        } else {
            codeDetailMapper.saveCode(vo);
        }
        codeManagementMapper.updateCount();
        return R.ok();
    }

    @Override
    public void saveBatchExcelData(List<CodeDetailsExcelVo> dataList) {
        if(!CollectionUtils.isEmpty(dataList)) {
            Set<CodeDetailsVo> data = new HashSet<>();
            for (CodeDetailsExcelVo excelVo : dataList) {
                CodeDetailsVo vo = new CodeDetailsVo();
                BeanUtils.copyProperties(excelVo, vo);
                vo.setName(excelVo.getName());
                vo.setValue(excelVo.getValue());
                vo.setLevel(levelMap.get(excelVo.getLevelName()));
                vo.setTypeId(typeMap.get(excelVo.getTypeName()));
                vo.setState("正常".equals(excelVo.getStateName()) ? 1 : 0);
                data.add(vo);
            }
            codeDetailMapper.addCodeList(data);
        }
    }

    /**
     * 入库前-批量校验数据
     *
     * @param dataList
     * @return
     */
    @Override
    public BatchDataResult<CodeDetailsExcelVo> checkBatchExcelData(List<CodeDetailsExcelVo> dataList) {
        List<CodeDetailsExcelVo> successList = new ArrayList<>();
        List<CodeDetailsExcelVo> failList = new ArrayList<>();
        List<CodeManagementVo> list = codeManagementMapper.selectAll(new Page<>(-1, -1), new CodeManagementParams());
        if(!CollectionUtils.isEmpty(dataList)) {
            Map<String, String> map = new HashMap<>();
            for(CodeManagementVo vo : list) {
                map.put(vo.getName(), vo.getName());
            }
            //1.返回码名称不为空 2.返回码值+类型名称+返回码名称的组合不能重复
            for(CodeDetailsExcelVo data : dataList) {
                CodeDetailsVo codeDetailsVo = codeDetailMapper.selectByValueAndTypeAndName(data.getValue(), typeMap.get(data.getTypeName()), data.getName());
                if (codeDetailsVo == null && map.get(data.getName())!=null){
                    successList.add(data);
                }else {
                    failList.add(data);
                }
            }
        }
        return new BatchDataResult<>(true, successList, failList);
    }

    @Override
    public boolean checkExcelData(CodeDetailsExcelVo data) {
        try {
			Field[] fields = data.getClass().getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
                if (field.get(data) == null) {
                    return false;
                }
            }
        } catch (IllegalAccessException e) {
            return false;
        }
        return true;
    }
}
